package com.neusoft.EYSystem.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.neusoft.EYSystem.dao.*;
import com.neusoft.EYSystem.po.*;
import com.neusoft.EYSystem.service.ClientNursingProjectService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.*;

@Service
public class ClientNursingProjectServiceImpl implements ClientNursingProjectService {
    // ✅ 工具方法：判断是否为合法字符串（排除 null、空串、"null"）
    private boolean isValid(String value) {
        return value != null && !value.trim().isEmpty() && !"null".equalsIgnoreCase(value.trim());
    }

    @Autowired
    private ClientNursingProjectDAO clientNursingProjectDAO;
    @Autowired
    private NursingLevelDAO nursingLevelDAO;
    @Autowired
    private ClientDAO clientDAO;
    @Autowired
    private NursingProjectDAO nursingProjectDAO;
    @Autowired
    private LevelProjectLinkDAO levelProjectLinkDAO;
    @Autowired
    private CaretakerClientDAO caretakerClientDAO;
    @Autowired
    private NursingRecordDAO nursingRecordDAO;

    @Override
    public PageResponseBean<List<ClientAndNursingLevel>> pageClientNursingProject(Long cur, Long number, Client client) {
        // 1. 查询全部符合条件的 Client
        QueryWrapper<Client> wrapperClient = new QueryWrapper<>();
        if (client != null && isValid(client.getName())) {
            wrapperClient.like("name", client.getName());
        }
        List<Client> allClients = clientDAO.selectList(wrapperClient);

        // 2. 构造全部 ClientAndNursingLevel 结果（可能重复）
        List<ClientAndNursingLevel> rawList = new ArrayList<>();
        for (Client c : allClients) {
            QueryWrapper<ClientNursingProject> wrapperClientNursingProject = new QueryWrapper<>();
            wrapperClientNursingProject.eq("client_id", c.getClientId());
            wrapperClientNursingProject.eq("status", 1);

            List<ClientNursingProject> clientProjects = clientNursingProjectDAO.selectList(wrapperClientNursingProject);
            for (ClientNursingProject clientNursingProject : clientProjects) {
                NursingLevel nursingLevel = nursingLevelDAO.selectById(clientNursingProject.getLevelId());
                if (nursingLevel != null) {
                    ClientAndNursingLevel combo = new ClientAndNursingLevel();
                    combo.setClient(c);
                    combo.setNursingLevel(nursingLevel);
                    rawList.add(combo);
                }
            }
        }

        // 3. 去重（根据 clientId 和 levelId）
        Set<String> seenKeys = new HashSet<>();
        List<ClientAndNursingLevel> distinctList = new ArrayList<>();

        for (ClientAndNursingLevel item : rawList) {
            String key = item.getClient().getClientId() + "-" + item.getNursingLevel().getLevelId();
            if (!seenKeys.contains(key)) {
                seenKeys.add(key);
                distinctList.add(item);
            }
        }

        // 4. 手动分页裁切 distinctList
        int fromIndex = (int) ((cur - 1) * number);
        int toIndex = Math.min(fromIndex + number.intValue(), distinctList.size());

        List<ClientAndNursingLevel> pageList = fromIndex < distinctList.size()
                ? distinctList.subList(fromIndex, toIndex)
                : List.of();

        // 5. 封装结果
        PageResponseBean<List<ClientAndNursingLevel>> rb = new PageResponseBean<>(pageList);
        rb.setTotal((long) distinctList.size());
        return rb;
    }


    @Override
    public Integer deleteStatusById(ClientNursingProject clientNursingProject) {
        UpdateWrapper<ClientNursingProject> uw = new UpdateWrapper<>();
        uw.eq("level_id", clientNursingProject.getLevelId());
        uw.eq("client_id", clientNursingProject.getClientId());
        clientNursingProject.setStatus("0");
        return clientNursingProjectDAO.update(clientNursingProject, uw);
    }

    @Override
    public PageResponseBean<List<ClientAndProject>> pageClientAndProject(Long cur, Long number, Client client, NursingProject nursingProject) {
        PageResponseBean<List<ClientAndProject>> response = new PageResponseBean<>();

        // 1. 查询符合客户名的 Client（完全匹配）
        if (client == null || client.getName() == null || client.getName().trim().isEmpty()) {
            response.setStatus(400);
            response.setMsg("客户名不能为空");
            return response;
        }

        QueryWrapper<Client> wrapperClient = new QueryWrapper<>();
        wrapperClient.eq("name", client.getName());
        Client c = clientDAO.selectOne(wrapperClient);
        if (c == null) {
            response.setStatus(404);
            response.setMsg("未找到对应客户");
            return response;
        }

        System.out.println(c.toString());

        // 2. 查询该 Client 的护理项目（状态为启用）
        QueryWrapper<ClientNursingProject> wrapperClientNursingProject = new QueryWrapper<>();
        wrapperClientNursingProject.eq("client_id", c.getClientId());
        wrapperClientNursingProject.eq("status", 1);

        List<ClientNursingProject> clientProjects = clientNursingProjectDAO.selectList(wrapperClientNursingProject);

        System.out.println(clientProjects.toString());

        List<ClientAndProject> fullList = new ArrayList<>();
        for (ClientNursingProject clientNursingProject : clientProjects) {

            NursingProject project = nursingProjectDAO.selectById(clientNursingProject.getProjectId());

            System.out.println("项目名：" + project.getName() + "，匹配关键词：" + nursingProject.getName());

            // 模糊匹配护理项目名（可选）
            if (nursingProject != null && nursingProject.getName() != null && !nursingProject.getName().trim().isEmpty()) {
                if (project == null || !project.getName().contains(nursingProject.getName())) {
                    continue;
                }
            }

            ClientAndProject combo = new ClientAndProject();
            combo.setClient(c);
            combo.setClientNursingProject(clientNursingProject);
            combo.setNursingProject(project);
            fullList.add(combo);
        }

        // 3. 手动分页
        int fromIndex = (int) ((cur - 1) * number);
        int toIndex = (int) Math.min(fromIndex + number, fullList.size());
        List<ClientAndProject> pageList = fromIndex < fullList.size() ? fullList.subList(fromIndex, toIndex) : new ArrayList<>();

        // 4. 构造返回对象
        response.setStatus(200);
        response.setMsg("查询成功");
        response.setData(pageList);
        response.setTotal(fullList.size());
        return response;
    }


    @Override
    public PageResponseBean<List<ClientAndProject>> pageClientAndProjectByName(Long cur, Long number, Client client) {
        // 1. 先查询全部符合条件的 Client
        QueryWrapper<Client> wrapperClient = new QueryWrapper<>();
        wrapperClient.eq("name", client.getName());
        List<Client> allClients = clientDAO.selectList(wrapperClient);
        // 2. 循环构造结果
        List<ClientAndProject> fullList = new ArrayList<>();
        for (Client c : allClients) {
            QueryWrapper<ClientNursingProject> wrapperClientNursingProject = new QueryWrapper<>();
            wrapperClientNursingProject.eq("client_id", c.getClientId());
            wrapperClientNursingProject.eq("status", 1);

            List<ClientNursingProject> clientProjects = clientNursingProjectDAO.selectList(wrapperClientNursingProject);
            for (ClientNursingProject clientNursingProject : clientProjects) {
                QueryWrapper<NursingProject> wrapperProject = new QueryWrapper<>();
                wrapperProject.eq("project_id", clientNursingProject.getProjectId());
                NursingProject nursingProject = nursingProjectDAO.selectOne(wrapperProject);
                ClientAndProject combo = new ClientAndProject();
                combo.setClient(c);
                combo.setClientNursingProject(clientNursingProject);
                combo.setNursingProject(nursingProject);
                fullList.add(combo);
            }
        }

        // 3. 手动分页裁切 fullList
        int fromIndex = (int) ((cur - 1) * number);
        int toIndex = (int) Math.min(fromIndex + number, fullList.size());

        List<ClientAndProject> pageList = fromIndex < fullList.size() ? fullList.subList(fromIndex, toIndex) : new ArrayList<>();

        // 4. 封装分页结果
        PageResponseBean<List<ClientAndProject>> rb = new PageResponseBean<>(pageList);
        rb.setTotal(fullList.size()); // 返回组合对象总条数
        return rb;
    }

    @Override
    public PageResponseBean<List<NursingProject>> pageNursingProject(Long cur, Long number, Client client, NursingLevel level) {
        PageResponseBean<List<NursingProject>> response;

        try {
            // 1. 查询客户
            QueryWrapper<Client> wrapperClient = new QueryWrapper<>();
            wrapperClient.eq("name", client.getName());
            Client client1 = clientDAO.selectOne(wrapperClient);

            if (client1 == null) {
                return new PageResponseBean<>(400, "客户不存在");
            }

            // 2. 查询该客户已购买的护理项目 project_id（按status = 1）
            QueryWrapper<ClientNursingProject> wrapperClientNursingProject = new QueryWrapper<>();
            wrapperClientNursingProject.eq("client_id", client1.getClientId());
            wrapperClientNursingProject.eq("status", 1);
            List<ClientNursingProject> purchased = clientNursingProjectDAO.selectList(wrapperClientNursingProject);

            List<Integer> purchasedProjectIds = purchased.stream()
                    .map(ClientNursingProject::getProjectId)
                    .toList();

            // 3. 查询该护理级别下所有项目 project_id
            QueryWrapper<LevelProjectLink> wrapperLink = new QueryWrapper<>();
            wrapperLink.eq("level_id", level.getLevelId());
            List<LevelProjectLink> levelLinks = levelProjectLinkDAO.selectList(wrapperLink);

            List<Integer> levelProjectIds = levelLinks.stream()
                    .map(LevelProjectLink::getProjectId)
                    .toList();

            // 4. 从 levelProjectIds 中去掉 purchasedProjectIds 得到未购买列表
            List<Integer> unpurchasedIds = levelProjectIds.stream()
                    .filter(id -> !purchasedProjectIds.contains(id))
                    .toList();

            if (unpurchasedIds.isEmpty()) {
                return new PageResponseBean<>(List.of()); // 无可购项目
            }

            // 5. 使用 In 进行分页查询
            IPage<NursingProject> page = new Page<>(cur, number);
            QueryWrapper<NursingProject> wrapperProject = new QueryWrapper<>();
            wrapperProject.in("project_id", unpurchasedIds); // 仅在有效 ID 中查找

            IPage<NursingProject> result = nursingProjectDAO.selectPage(page, wrapperProject);

            // 6. 封装结果
            response = new PageResponseBean<>(result.getRecords());
            response.setTotal(result.getTotal());

        } catch (Exception e) {
            e.printStackTrace();
            response = new PageResponseBean<>(500, "查询未购买护理项目失败: " + e.getMessage());
        }

        return response;
    }

    @Override
    public PageResponseBean<List<ClientAndNursingLevel>> pageClientNursingProjectByCaretaker(Long cur, Long number, Client client, User user) {
        // 1. 查找该护工正在服务的客户ID列表（is_servered = true）
        QueryWrapper<CaretakerClient> bindWrapper = new QueryWrapper<>();
        bindWrapper.eq("caretaker_id", user.getUserId());
        bindWrapper.eq("is_servered", 1);
        List<CaretakerClient> caretakers = caretakerClientDAO.selectList(bindWrapper);
        List<Integer> clientIds = caretakers.stream()
                .map(CaretakerClient::getClientId)
                .toList();

        if (clientIds.isEmpty()) {
            return new PageResponseBean<>(List.of()); // 无服务对象
        }

        // 2. 查询全部符合条件的 Client
        QueryWrapper<Client> wrapperClient = new QueryWrapper<>();
        wrapperClient.in("client_id", clientIds);
        if (client != null && isValid(client.getName())) {
            wrapperClient.like("name", client.getName());
        }
        List<Client> allClients = clientDAO.selectList(wrapperClient);

        // 3. 构造全部 ClientAndNursingLevel 结果
        List<ClientAndNursingLevel> rawList = new ArrayList<>();
        for (Client c : allClients) {
            QueryWrapper<ClientNursingProject> wrapperClientNursingProject = new QueryWrapper<>();
            wrapperClientNursingProject.eq("client_id", c.getClientId());
            wrapperClientNursingProject.eq("status", 1);
            List<ClientNursingProject> clientProjects = clientNursingProjectDAO.selectList(wrapperClientNursingProject);

            for (ClientNursingProject clientNursingProject : clientProjects) {
                NursingLevel nursingLevel = nursingLevelDAO.selectById(clientNursingProject.getLevelId());
                if (nursingLevel != null) {
                    ClientAndNursingLevel combo = new ClientAndNursingLevel();
                    combo.setClient(c);
                    combo.setNursingLevel(nursingLevel);
                    rawList.add(combo);
                }
            }
        }

        // 4. 去重：根据 clientId + levelId 组合去重
        Set<String> seenKeys = new HashSet<>();
        List<ClientAndNursingLevel> distinctList = new ArrayList<>();

        for (ClientAndNursingLevel item : rawList) {
            String key = item.getClient().getClientId() + "-" + item.getNursingLevel().getLevelId();
            if (!seenKeys.contains(key)) {
                seenKeys.add(key);
                distinctList.add(item);
            }
        }

        // 5. 手动分页
        int fromIndex = (int) ((cur - 1) * number);
        int toIndex = Math.min(fromIndex + number.intValue(), distinctList.size());
        List<ClientAndNursingLevel> pageList = fromIndex < distinctList.size() ? distinctList.subList(fromIndex, toIndex) : List.of();

        // 6. 构建响应
        PageResponseBean<List<ClientAndNursingLevel>> response = new PageResponseBean<>();
        response.setStatus(200);
        response.setMsg("success");
        response.setData(pageList);
        response.setTotal((long) distinctList.size());

        return response;
    }

    @Override
    public Integer deleteStatusOneById(ClientNursingProject clientNursingProject) {
        UpdateWrapper<ClientNursingProject> uw = new UpdateWrapper<>();
        uw.eq("level_id", clientNursingProject.getLevelId());
        uw.eq("client_id", clientNursingProject.getClientId());
        uw.eq("project_id", clientNursingProject.getProjectId());
        clientNursingProject.setStatus("0");
        return clientNursingProjectDAO.update(clientNursingProject, uw);
    }

    @Override
    public ResponseBean<Integer> judgeNursingProjectCost(Long clientId, Long levelId, Long projectId) {
        try {
            // 查询购买记录（状态为1）
            QueryWrapper<ClientNursingProject> query = new QueryWrapper<>();
            query.eq("client_id", clientId)
                    .eq("level_id", levelId)
                    .eq("project_id", projectId)
                    .eq("status", 1);

            ClientNursingProject purchase = clientNursingProjectDAO.selectOne(query);
            if (purchase == null || purchase.getQuantity() <= 0) {
                return new ResponseBean<>(0); // 无购买记录或已用尽
            }

            return new ResponseBean<>(1); // 还有剩余服务
        } catch (Exception e) {
            e.printStackTrace();
            return new ResponseBean<>(500, "判断护理服务剩余次数失败");
        }
    }

    @Override
    public ResponseBean<Integer> judgeNursingProjectExpiration(Long clientId, Long levelId, Long projectId) {
        try {
            // 查询有效的护理项目
            QueryWrapper<ClientNursingProject> qw = new QueryWrapper<>();
            qw.eq("client_id", clientId)
                    .eq("level_id", levelId)
                    .eq("project_id", projectId)
                    .eq("status", 1);

            ClientNursingProject project = clientNursingProjectDAO.selectOne(qw);
            if (project == null || project.getEndDate() == null) return new ResponseBean<>(1); // 视为已过期

            // 比较日期
            LocalDate now = LocalDate.now();
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd"); // 或 "yyyy-MM-dd HH:mm:ss" 看你的格式
            LocalDate endDate = LocalDate.parse(project.getEndDate(), formatter);

            return new ResponseBean<>(now.isAfter(endDate) ? 1 : 0);
        } catch (Exception e) {
            e.printStackTrace();
            return new ResponseBean<>(500, "判断护理服务是否到期失败");
        }
    }

    @Override
    public ResponseBean<List<ClientAndProject>> judgeNursingProject() {
        ResponseBean<List<ClientAndProject>> response = new ResponseBean<>();
        try {
            List<ClientAndProject> resultList = new ArrayList<>();

            // 查询所有状态为 1 的护理项目
            QueryWrapper<ClientNursingProject> wrapper = new QueryWrapper<>();
            wrapper.eq("status", 1);
            List<ClientNursingProject> projectList = clientNursingProjectDAO.selectList(wrapper);

            LocalDate now = LocalDate.now();

            for (ClientNursingProject cnp : projectList) {
                if (cnp.getEndDate() == null || cnp.getQuantity() == null) continue;
                DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
                LocalDate endDate = LocalDate.parse(cnp.getEndDate(), formatter);
                long daysLeft = ChronoUnit.DAYS.between(now, endDate);

                if (daysLeft >= 0 && daysLeft <= 7 && cnp.getQuantity() > 0) {
                    Client client = clientDAO.selectById(cnp.getClientId());
                    NursingProject project = nursingProjectDAO.selectById(cnp.getProjectId());

                    if (client != null && project != null) {
                        ClientAndProject cap = new ClientAndProject();
                        cap.setClient(client);
                        cap.setClientNursingProject(cnp);
                        cap.setNursingProject(project);
                        resultList.add(cap);
                    }
                }
            }
            // 按 client.name 升序、quantity 降序排序
            resultList.sort(
                    Comparator.comparing((ClientAndProject cap) -> cap.getClient().getName(), Comparator.nullsLast(String::compareTo))
                            .thenComparing((ClientAndProject cap) -> cap.getClientNursingProject().getQuantity(), Comparator.reverseOrder())
            );

            response.setStatus(200);
            response.setMsg("查询成功");
            response.setData(resultList);
        } catch (Exception e) {
            e.printStackTrace();
            response.setStatus(500);
            response.setMsg("查询即将到期护理项目失败：" + e.getMessage());
            response.setData(null);
        }

        return response;
    }

}
